const sessionService = require('./sessionService')
const util = require('../utils/util')
const rsa = require('../utils/rsaUtl')
const aes = require('../utils/aesUtil')
const conf = require('../config')

const getDefaultOptions = () => {
  return {
    header: {
      'Authorization': 'Bearer ' + sessionService.get('accessToken')
    },
    dataType: {
      'content-type': 'application/json'
    }
  }
}
const request = (url, method, params) => {
  const defaultOptions = getDefaultOptions()
  if (method.toLowerCase() === 'post') {
    if(params) {
      //加密
      var nonceStr = util.createNonceStr(16);
      var randomKey = rsa.encrypt(nonceStr);
      var requestData = {
        data: aes.encrypt(nonceStr,params),
        randomKey: randomKey
      };
      params = requestData;
    }
  }
  return new Promise((resolve, reject) => {
    let options = {
      url: url,
      method: method,
      data: params,
      success(res) {
        // 判断不同的返回码 200/404
        if (res.statusCode === 200) {
          try {
            let data = JSON.parse(res.data);
            if (data && data.code == 0) {
              // console.log("resp",data)
              //解密
              if (method.toLowerCase() === 'post') {
                res.data = aes.decrypt(rsa.decrypt(data.randomKey),data.data)
                console.log(res.data);
              } else {
                es.data = data.data;
              }
            } else if (data.code === -3) {
              console.error(data.msg);
            } else if (data.code === -2){
              console.log("用户未登录-ajax");
            }
          } catch (e) {
            console.error('出错了，' + e + ',接口返回数据:' + res.data);
          }
        } else if(res.statusCode === 404) {
          console.log('404');
        }
        resolve(res)
      },
      fail(err) {
        reject(err)
      }
    }
    options = Object.assign({}, defaultOptions, options)
    wx.request(options)
  })
}


// 获取accessToken
function getAccessToken(callback) {
  let accesstoken = sessionService.get('accessToken')
  if (accesstoken) {
    callback(accesstoken);
  } else {
    let data = {
      code: "123"
    };
    request(conf.service.getToken, 'post', data).then(res => {
      let accesstoken = res.data.accessToken;
        if (typeof (callback) === 'function' && accesstoken) {
          sessionService.set('accessToken',accesstoken)
          callback(accesstoken);
        }
      }
    ).then(err => {
      console.error("err=======",err)
    })
  }
 }
 
 // 封装request请求
 const commonRequest = options => {
  if(options) {
    getAccessToken(function (accesstoken){
      // header 设置Content-Type，accesstoken, usertoken, noncestr, timestamp等信息，与后台协商好
      if(options.header === undefined || options.header === null) {
        options.header = {};
      }   
      options.header['Content-Type'] = 'application/json; charset=UTF-8';
      options.header['accessToken'] = sessionService.get('accessToken');
      // 自定义getNoncestr()设置随机字符串，getTimestamp()获取时间戳
      let nonce = util.createNonceStr(16);
      let timestamp = new Date().getTime();
      if (timestamp) {
        options.header['timestamp'] = timestamp;
      } 
      if (nonce) {
        options.header['nonce'] = nonce;
      }
      // method、data
      if (options.method === undefined || options.method === null) {
        options.method = 'post';
      }
      if (options.method.toLowerCase() === 'post') {
        if(options.data) {
          //加密
          var nonceStr = util.createNonceStr(16);
          var randomKey = rsa.encrypt(nonceStr);
          var requestData = {
            data: aes.encrypt(nonceStr,options.data),
            randomKey: randomKey
          };
          options.data = requestData;
        }
      }
      //success
      if (options.success && typeof(options.success) === 'function') {
        let successCallback = options.success;
        options.success = function(res) {
        // 判断不同的返回码 200/404
        if (res.statusCode === 200) {
          try {
            // console.log("==="+res.data.data)
            // const resp = JSON.parse(res.data)
            let data = res.data;
            if (data && data.code == 0) {
              // console.log("resp",data)
              //解密
              if (options.method.toLowerCase() === 'post') {
                res.data = aes.decrypt(rsa.decrypt(data.randomKey),data.data);
                console.log(res.data);
              } else {
                res.data = data.data;
              }
            } else if (data.code === -3) {
              console.error(data.msg);
            } else if (data.code === -2){
              console.log("用户未登录-ajax");
            }
            //调用自定义的success
            successCallback(res);
          } catch (e) {
            console.error('出错了，' + e + ',接口返回数据:' + res.data);
          }
        } else if(res.statusCode === 404) {
          console.log('404');
        }
        }
      }
    //执行微信的请求
    wx.request(options);
   });
  } 
 }

module.exports = {
  get: (url, params) => {
    return request(url, 'get', params)
  },

  post: (url, params) => {
    return request(url, 'post', params)
  },

  put: (url, params) => {
    return request(url, 'delete', params)
  },
  commonRequest
}
